package com.zerui.manager.device.scheduled;

import com.zerui.manager.device.Device;
import com.zerui.manager.device.custom.DeviceCustom;
import com.zerui.manager.device.gateway.DeviceGateWay;
import com.zerui.manager.web.enums.DeviceAccessStatusEnum;
import com.zerui.manager.web.enums.DeviceFromEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.sql.Time;
import java.text.ParseException;
import java.time.LocalTime;
import java.util.List;

/**
 * @author lvfengjun
 * @title: DevcieScheduled
 * @description:
 * @date 2023/10/21 9:33
 */

@Slf4j
@Component
public class DevcieScheduled {

	@Resource
	private DeviceGateWay deviceGateWay;

	/**
	 * 每一分钟执行一次  执行在时间范围内的开关数据
	 */
	@Scheduled(cron = "0 */1 * * * ?")
	public void deviceCurfewTime() throws ParseException {
		LocalTime now = LocalTime.now();
		LocalTime localTime = now.plusMinutes(1);

		Time startTime = Time.valueOf(now);
		Time endTime = Time.valueOf(localTime);
		// 获取任务状态 要开门的 任务
		List<DeviceCustom> deviceOpenList = deviceGateWay.selectDeviceCurfewTimeStart2(startTime, endTime, DeviceAccessStatusEnum.OPEN.getCode());
		deviceOpenList.forEach(device -> {
			if (device.getDeviceFrom() == DeviceFromEnum.FROM_IOT.getCode()) { // IOT设备
				try {
					Device param = new Device();
					param.setDeviceId(device.getDeviceId());
					//todo 理解错误 暂时先和开关用 一个枚举 做物联网关交互
					param.setTimedTaskStatus(DeviceAccessStatusEnum.OPEN.getCode());
					deviceGateWay.iotDeviceAutoOpenEnable(param);
				} catch (Exception e) {
					log.error("调用IoT网关出错，错误信息 {}", e.getMessage());
				}
			} else if (device.getDeviceFrom() == DeviceFromEnum.FROM_ICC.getCode()) { // ICC设备
				device.setTimedTaskStatus(DeviceAccessStatusEnum.OPEN.getCode());
				deviceGateWay.iccDeviceAutoOpenEnable(device);
			}
		});

		// 获取任务状态 要关门的 任务
		List<DeviceCustom> deviceCloseList = deviceGateWay.selectDeviceCurfewTimeEnd2(startTime, endTime, DeviceAccessStatusEnum.OPEN.getCode());
		deviceCloseList.forEach(device -> {
			if (device.getDeviceFrom() == DeviceFromEnum.FROM_IOT.getCode()) { // IOT设备
				try {
					Device param = new Device();
					param.setDeviceId(device.getDeviceId());
					param.setTimedTaskStatus(DeviceAccessStatusEnum.CLOSE.getCode());
					deviceGateWay.iotDeviceAutoOpenEnable(param);
				} catch (Exception e) {
					log.error("调用IoT网关出错，错误信息 {}", e.getMessage());
				}
			} else if (device.getDeviceFrom() == DeviceFromEnum.FROM_ICC.getCode()) { // ICC设备
				device.setTimedTaskStatus(DeviceAccessStatusEnum.CLOSE.getCode());
				deviceGateWay.iccDeviceAutoOpenEnable(device);
			}
		});

	}
}
